/**
 * Author: Sonny Sandberg
 */
package database;

import java.sql.*;

public class Database 
{
    private Connection conn;
    private Statement stmt;
    private ResultSet rs;
    private DbIniParser db_values;
    
    /**
     * Connection to database is established as soon as object is created.
     * @throws ClassNotFoundException
     * @throws SQLException 
     */
    public Database() throws ClassNotFoundException, SQLException
    {
        db_values = new DbIniParser();
    }
    
    /**
     * Connect to DB
     * @throws ClassNotFoundException
     * @throws SQLException 
     */
    public void connectToDB() throws ClassNotFoundException, SQLException
    {
        //Driveren loades - kræver at MySQL JDBC Driver er tilføjet under Libraries
        Class.forName("com.mysql.jdbc.Driver");
        //Der oprettes et Connection-objekt med port, databasenavn, brugernavn og password
        
        conn = DriverManager.getConnection("jdbc:mysql://"+db_values.getHost()+":"+db_values.getPort()+"/"+db_values.getDatabase()+"", db_values.getDB_User(), db_values.getDB_Pass());
    }
    
    /**
     * Use this to close database connection opened by object
     */
    public void closeDB() throws SQLException
    {
        conn.close();
    }
    
    /**
     * 
     * @param sql for example (SELECT column_one, column2, column3 FROM table WHERE id = 1)
     * If you want to call a procedure (CALL procedureName();)
     * If you want to call a function (SELECT functionName();)
     * @return ResultSet
     * @throws SQLException 
     */
    public ResultSet query(String sql) throws SQLException
    {
        stmt = conn.createStatement();
        return stmt.executeQuery(sql);
    }
    
    /**
     * 
     * @param sql for example (INSERT INTO table (column_one, column2, column3) VALUES ("1", "2", "3")
     * If you want to call a procedure (CALL procedureName();)
     * @return int - affected_rows
     * @throws SQLException 
     */
    public int manipulateDB(String sql) throws SQLException
    {        
        stmt = conn.createStatement();
        return stmt.executeUpdate(sql);
    }
}